import json
import os
import shutil
from urllib import request
import tornado
from tornado import gen
from tornado import web

import sys
sys.path.append("..")

from .base import BaseHandler
from utils.pathutil import PathBuilder
from utils.dbutil import MySQLConnection
from utils.dockerutil import JupyterServiceUtil
from utils.jsonresult import JsonResult, json_result_encoder

# 登录
class LoginHandler(BaseHandler):
    @gen.coroutine
    def get(self):
        self.clear_cookie("user_info")
        self.render('login.html', error=None)
    
    @gen.coroutine
    def post(self):
        username = self.get_argument("username")
        password = self.get_argument("password")
        conn = MySQLConnection.get_connection()
        try:
            with conn.cursor() as cursor:
                sql = "select accountid, accountname, truename from account where role=1 and \
                    accountname='{}' and password='{}'".format(username, password)
                cursor.execute(sql)
                account = cursor.fetchone()
        finally:
            conn.close()
                
        if account:
            accountid = account['accountid']
            accountname = account['accountname']
            truename = account['truename']            
            self.set_secure_cookie("user_info", str(accountid) + "-" + accountname + "-" + truename)
            self.redirect("/")
        else:
            self.render('login.html', error='错误的用户名或密码')

class LogoutHandler(BaseHandler):
    @web.authenticated
    @gen.coroutine
    def get(self):
        self.clear_cookie("user_info")
        self.redirect('/account_login')

class PasswordHandler(BaseHandler):
    @web.authenticated
    @gen.coroutine
    def get(self):
        user = self.get_current_user()
        self.render('password.html', user=user, password_message=None)
    
    @web.authenticated
    @gen.coroutine
    def post(self):
        user = self.get_current_user()
        if user:
            password = self.get_argument('newpassword', default='')
            confirm = self.get_argument('confirmpassword', default='')
            password_message = None
            if password != confirm or password == '':
                password_message = '新密码为空或不匹配'
            else:
                # 修改密码
                conn = MySQLConnection.get_connection()
                try:
                    with conn.cursor() as cursor:
                        sql = "update account set password={} where accountid={}".format(password, user['accountid'])
                        cursor.execute(sql)
                        conn.commit()
                        password_message = '密码修改成功' 
                except:
                    password_message = '密码修改失败，请联系管理员！' 
                finally:
                    conn.close()
        else:
            password_message = '用户未登录'
        
        self.render('password.html', user=user, password_message = password_message)


# 当前学生正在运行的容器信息
class ContainerHandler(BaseHandler):
    @web.authenticated
    @gen.coroutine
    def get(self):
        user = self.get_current_user()
        containers = JupyterServiceUtil.find_user_all_services(user["accountname"])
        self.render('accountcontainer.html', user=user, containers = containers)
    
    @web.authenticated
    @gen.coroutine
    def delete(self):
        user = self.get_current_user()
        container = self.get_argument("container")
        # 只允许停止本人的服务
        if container.find(user['accountname']) != -1:            
            JupyterServiceUtil.remove_service(container)
        
        self.write(json.dumps(True))
        self.finish()

default_handlers = [    
    (r'/account_login', LoginHandler),
    (r'/account_logout', LogoutHandler),
    (r'/account_pwd', PasswordHandler),
    (r'/account_container', ContainerHandler)
]